package own.stu.jobgib.playown.juc;

import io.netty.util.internal.PlatformDependent;

import java.util.Queue;
import java.util.concurrent.*;

public class MpscQueueTest {

    public static void main2(String[] args) {
        System.out.println(ThreadLocalRandom.current().nextInt(0, 10));
    }

    public static void main(String[] args) throws InterruptedException {
        Queue<Integer> queue = PlatformDependent.newMpscQueue(1024 * 1024);
//        LinkedBlockingDeque<Integer> queue = new LinkedBlockingDeque<>();

        CountDownLatch latch = new CountDownLatch(5);
        Integer END_NUM = 1024;

        new Thread(() -> {

            int cnt = 0;
            while (true) {
                Integer num = queue.poll();
                if (num == null) {
                    try {
                        TimeUnit.MILLISECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    if (num == END_NUM) {
                        cnt++;
                    }
                }
                if (cnt == 4)
                    break;
            }
            latch.countDown();
        }).start();

        ExecutorService executorService = Executors.newFixedThreadPool(4);

        for (int j = 0; j < 4; j++)
            executorService.submit(() -> {
                try {
                    for (int i = 0; i < 10_000_000; i++) {
                        int num = ThreadLocalRandom.current().nextInt(0, 10);
//                        TimeUnit.MILLISECONDS.sleep(num);
                        queue.add(num);

                    }
                    queue.add(END_NUM);

                    latch.countDown();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        System.out.println(" --------- ");
        long start = System.nanoTime();
        latch.await();
        System.out.println("cost : " + (System.nanoTime() - start) / 1000 / 1000);

    }
}
